package com.maiji.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.maiji.cloud.entities.shopingmall.ShareOrderRule;
import com.maiji.cloud.entities.shopingmall.ShipmentsInfoEntity;
import com.maiji.cloud.entities.shopingmall.ShopingOrderEditLog;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.request.shopingmall.*;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseMetaResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.shopingmall.LogisticsInfoResData;
import com.maiji.cloud.response.shopingmall.ShareOrderLogResData;
import com.maiji.cloud.response.shopingmall.ShopingOrderResData;
import com.maiji.cloud.response.shopingmall.ShopingOrderStatusCountResData;
import com.maiji.cloud.service.*;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/shopingOrder/")
public class ShopingOrderController extends BaseContronller{

	 Logger logger = LoggerFactory.getLogger(ShopingOrderController.class);
    @Autowired
    private ShopingOrderService shopingOrderService;
    @Autowired
    private ShipmentsInfoService shipmentsInfoService;
    @Autowired
    private ShopingAddressService shopingAddressService;
    @Autowired
    private ShopingOrderEditLogService shopingOrderEditLogService;
    @Autowired
    private ShopingOrderRefundService shopingOrderRefundService;
    @Autowired
    private ShareOrderLogService shareOrderLogService;
    @Autowired
    private ShareOrderHelpLogService shareOrderHelpLogService;

    /**
     *  手动发货修改
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderPrintUpdate")
    public BaseResDto orderPrintUpdate (@RequestBody BaseDataReqDto<OrderPrintReqData> baseDataReqDto) {
        OrderPrintReqData data = baseDataReqDto.getData();
        if (data == null) return new BaseDataResDto(Status.ERROR);
        return shipmentsInfoService.orderPrintUpdate(data);
    }

    /**
     *  手动发货
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderPrintManual")
    public BaseResDto orderPrintManual (@RequestBody BaseDataReqDto<OrderPrintReqData> baseDataReqDto) {
        OrderPrintReqData data = baseDataReqDto.getData();
        if (data == null) return new BaseDataResDto(Status.ERROR);
        return shipmentsInfoService.orderPrintManual(data);
    }

    /**
     *  打印订单发货的电子面单
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderPrint")
    public BaseDataResDto<List<ShipmentsInfoEntity>> orderPrintAll (@RequestBody BaseDataReqDto<List<OrderPrintReqData>> baseDataReqDto) {
        List<OrderPrintReqData> data = baseDataReqDto.getData();
        if (data == null || data.size() == 0) return new BaseDataResDto(Status.ERROR);
        return shipmentsInfoService.orderPrintAll(data);
    }

    /**
     *  打印订单发货的电子面单_增加分单
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderPrintAdd")
    public BaseDataResDto<ShipmentsInfoEntity> orderPrintAdd (@RequestBody BaseDataReqDto<OrderPrintReqData> baseDataReqDto) {
        OrderPrintReqData data = baseDataReqDto.getData();
        if (data == null) return new BaseDataResDto(Status.ERROR);
        return shipmentsInfoService.orderPrintAdd(data);
    }

    /**
     *  新单号重新打印电子面单
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderPrintNew")
    public BaseDataResDto<ShipmentsInfoEntity> orderPrintNew (@RequestBody BaseDataReqDto<OrderPrintReqData> baseDataReqDto) {
        OrderPrintReqData data = baseDataReqDto.getData();
        if (data == null) return new BaseDataResDto(Status.ERROR);
        return shipmentsInfoService.orderPrintNew(data);
    }

    /**
     *  获取订单发货信息列表（已打印电子面单 / 代发货）
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllShipmentsInfos")
    public BaseMetaResDto<List<List<ShipmentsInfoEntity>>> findAllShipmentsInfos (@RequestBody BaseDataReqDto<ShipmentsInfoReqData> baseDataReqDto) {
        ShipmentsInfoReqData data = baseDataReqDto.getData();
        if (data == null) return new BaseMetaResDto(Status.ERROR);
        return shipmentsInfoService.findAllShipmentsInfos(data);
    }

    /**
	 * 根据订单id获取运单编号集合
	 * @param param
	 * @return
	 */
	@PostMapping("getTrackingNumberByOrderId")
	public BaseDataResDto<List<String>> getTrackingNumberByOrderId(@RequestBody BaseDataReqDto<String> param) {
		return shopingOrderService.getTrackingNumberByOrderId(param);
	}
	
	/**
	 * 根据运单号获取物流轨迹
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@PostMapping("getLogisticsInfoByExpressNo")
	public BaseDataResDto<LogisticsInfoResData> getLogisticsInfoByExpressNo(@RequestBody BaseDataReqDto<String> param) throws Exception{
		return shopingOrderService.getLogisticsInfoByExpressNo(param);
	}

    /**
     *  订单发货
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderSend")
    public BaseResDto orderSend (@RequestBody BaseDataReqDto<List<ShipmentsInfoEntity>> baseDataReqDto) {
        List<ShipmentsInfoEntity> data = baseDataReqDto.getData();
        if (data == null || data.size() == 0) return new BaseResDto(Status.ERROR);
        return shipmentsInfoService.orderSend(data);
    }

    /**
     *  初始化订单数据
     * @param orderInitReqDto
     * @param token
     * @return
     */
    @PostMapping("initOrder")
    public BaseDataResDto<ShopingOrderResData> initOrder (@RequestBody OrderInitReqDto orderInitReqDto, @RequestHeader("maijiToken") String token) {
        OrderInitReqDto.OrderInitReqData data = orderInitReqDto.getData();
        if (data == null) return new BaseDataResDto<>(Status.ERROR);
        return shopingOrderService.initOrder(data, getUserId(token), token);
    }

    /**
     *  刷新订单数据
     * @param orderRefreshReqDto
     * @param token
     * @return
     */
    @PostMapping("refreshOrder")
    public BaseDataResDto<ShopingOrderResData> refreshOrder (@RequestBody OrderRefreshReqDto orderRefreshReqDto,
                                                             @RequestHeader("maijiToken") String token) {
        OrderRefreshReqDto.OrderRefreshReqData data = orderRefreshReqDto.getData();
        if (data == null) return new BaseDataResDto<>(Status.ERROR);
        return shopingOrderService.refreshOrder(data, getUserId(token), token);
    }

    /**
     *  提交订单数据
     * @param orderSubmitReqDto
     * @param token
     * @return
     */
    @PostMapping("orderSubmit")
    public BaseDataResDto<ShopingOrderResData> orderSubmit (@RequestBody OrderSubmitReqDto orderSubmitReqDto,
                                                                  @RequestHeader("maijiToken") String token) {
        OrderSubmitReqDto.OrderSubmitReqData data = orderSubmitReqDto.getData();
        if (data == null) return new BaseDataResDto(Status.ERROR);
        return shopingOrderService.orderSubmit(data, getUserId(token), token);
    }

    /**
     *  获取订单详情
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findOrderById")
    public BaseDataResDto<ShopingOrderResData> findOrderById (@RequestBody BaseDataReqDto<String> baseDataReqDto) {
        String orderId = baseDataReqDto.getData();
        if (orderId == null) return new BaseDataResDto(Status.PARAMETERERROR);
        return shopingOrderService.findOrderById(orderId);
    }

    /**
     *  取消订单
     * @param orderCancelReqDto
     * @return
     */
    @PostMapping("cancelOrderById")
    public BaseDataResDto<ShopingOrderResData> cancelOrderById (@RequestBody OrderCancelReqDto orderCancelReqDto) {
        String orderId = orderCancelReqDto.getData().getOrderId();
        String cancelReason = orderCancelReqDto.getData().getCancelReason();
        if (StringUtil.isBlank(orderId) || StringUtil.isBlank(cancelReason)) return new BaseDataResDto(Status.PARAMETERERROR);
        return shopingOrderService.cancelOrderById(orderId, cancelReason);
    }

    /**
     *  删除 / 批量删除 订单
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("delOrdersByIds")
    public BaseResDto delOrdersByIds (@RequestBody BaseDataReqDto<List<String>> baseDataReqDto) {
        List<String> orderIds = baseDataReqDto.getData();
        if (orderIds == null || orderIds.size() == 0) return new BaseDataResDto(Status.PARAMETERERROR);
        return shopingOrderService.delOrdersByIds(orderIds);
    }

    /**
     *  根据订单状态获取用户订单列表
     * @param baseDataReqDto
     * @param token
     * @return
     */
    @PostMapping("findAllOrdersByUserId")
    public BaseMetaResDto<List<ShopingOrderResData>> findAllOrdersByUserId (@RequestBody BaseDataReqDto<Integer> baseDataReqDto,
                                                                    @RequestHeader("maijiToken") String token) {
        Integer status = baseDataReqDto.getData();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        if (metaData == null) return new BaseMetaResDto<>(Status.PARAMETERERROR);
        OrderFindAllReqData orderFindAllReqData = new OrderFindAllReqData().setStatus(status).setRefundStatuses(Arrays.asList(-1));
        return shopingOrderService.findAllOrders(orderFindAllReqData, metaData, getUserId(token));
    }

    /**
     *  根据商品名关键词搜索用户订单列表
     * @param baseDataReqDto
     * @param token
     * @return
     */
    @PostMapping("findOrdersByUserId")
    public BaseMetaResDto<List<ShopingOrderResData>> findOrdersByUserId (@RequestBody BaseDataReqDto<String> baseDataReqDto,
                                                                    @RequestHeader("maijiToken") String token) {
        String goodsName = baseDataReqDto.getData();
        return shopingOrderService.findOrdersByUserId(goodsName, getUserId(token));
    }

    /**
     *  获取用户退款/售后订单列表
     * @param baseDataReqDto
     * @param token
     * @return
     */
    @PostMapping("findAllRefundOrders")
    public BaseMetaResDto<List<ShopingOrderResData>> findAllRefundOrders (@RequestBody BaseDataReqDto baseDataReqDto,
                                                                          @RequestHeader("maijiToken") String token) {
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        if (metaData == null) return new BaseMetaResDto<>(Status.PARAMETERERROR.setMessage("缺失分页参数！"));
        if (metaData.getPage() ==0 || metaData.getSize() == 0) return new BaseMetaResDto<>(Status.PARAMETERERROR.setMessage("分页参数错误"));
        OrderFindAllReqData orderFindAllReqData = new OrderFindAllReqData().setRefundStatuses(Arrays.asList(0, 1, 2, 3, 4, 5)).setOrderBy("refund_date");
        return shopingOrderRefundService.findAllRefundOrders(orderFindAllReqData, metaData, getUserId(token));
    }

    /**
     *  获取所有订单列表
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllOrders")
    public BaseMetaResDto<List<ShopingOrderResData>> findAllOrders (@RequestBody BaseDataReqDto<OrderFindAllReqData> baseDataReqDto) {
        OrderFindAllReqData data = baseDataReqDto.getData();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        if (metaData == null) return new BaseMetaResDto<>(Status.PARAMETERERROR);
        return shopingOrderService.findAllOrders(data, metaData, null);
    }

    /**
     *  获取所有订单列表：待发货
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllOrders1")
    public BaseMetaResDto<List<List<ShopingOrderResData>>> findAllOrders1 (@RequestBody BaseDataReqDto<OrderFindAllReqData> baseDataReqDto) {
        OrderFindAllReqData data = baseDataReqDto.getData();
        ReqMetaData metaData = new ReqMetaData().setPage(1).setSize(9999);
        return shopingOrderService.findAllOrders1(data, metaData);
    }

    /**
     *  提醒订单发货
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("remindSendByOrderId")
    public BaseResDto remindSendByOrderId (@RequestBody BaseDataReqDto<String> baseDataReqDto) {
        String orderId = baseDataReqDto.getData();
        if (StringUtil.isBlank(orderId)) return new BaseMetaResDto<>(Status.PARAMETERERROR);
        return shopingOrderService.remindSendByOrderId(orderId);
    }

    /**
     *  获取各个状态的订单数量
     * @return
     */
    @PostMapping("findAllShopingOrderStatusCount")
    public BaseDataResDto<List<ShopingOrderStatusCountResData>> findAllShopingOrderStatusCount (@RequestHeader("maijiToken") String token) {
        return shopingOrderService.findAllShopingOrderStatusCount(getUserId(token));
    }
    
    /**
     * 积分兑换商品
     * @param param
     * @return
     */
    @PostMapping("integralExchangeGoods")
    public BaseDataResDto<ShopingOrderResData> integralExchangeGoods(@RequestBody BaseDataReqDto<IntegralExchangeGoodsReqData> param,
                                                                     @RequestHeader("maijiToken") String maijiToken){
    	logger.info("ShopingOrderController.integralExchangeGoods,param is {},maijiToken is {}", JSON.toJSONString(param), maijiToken);
        return shopingOrderService.integralExchangeGoods(param, getUserId(maijiToken));
    }

    /**
     *  获取打印快递单代发货数量
     * @return
     */
    @PostMapping("findAllShopingOrderSendStatusCount")
    public BaseDataResDto<Integer> findAllShopingOrderSendStatusCount () {
        return shipmentsInfoService.findAllShopingOrderSendStatusCount();
    }

    /**
     * 获取订单返现分享助力规则修改记录列表
     * @return
     */
    @PostMapping("findAllShareOrderRuleLogs")
    public BaseDataResDto<List<ShareOrderRule>> findAllShareOrderRuleLogs(@RequestBody BaseDataReqDto<List<Date>> baseDataReqDto){
        List<Date> data = baseDataReqDto.getData();
        return shareOrderLogService.findAllShareOrderRuleLogs(data);
    }

    /**
     * 修改订单返现分享助力规则
     * @return
     */
    @PostMapping("updShareOrderRule")
    public BaseResDto updShareOrderRule(@RequestBody BaseDataReqDto<ShareOrderRule> baseDataReqDto){
        ShareOrderRule data = baseDataReqDto.getData();
        return shareOrderLogService.updShareOrderRule(data);
    }

    /**
     * 获取订单返现分享助力规则
     * @return
     */
    @PostMapping("findShareOrderRule")
    public BaseDataResDto<ShareOrderRule> findShareOrderRule(){
        return shareOrderLogService.findShareOrderRule();
    }

    /**
     * 根据订单ID判断订单是否可以助力返现
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("ifCanShareOrder")
    public BaseDataResDto<ShareOrderLogResData> ifCanShareOrder(@RequestBody BaseDataReqDto<String> baseDataReqDto,
                                                                @RequestHeader("maijiToken") String maijiToken){
        String orderId = baseDataReqDto.getData();
        if (StringUtil.isBlank(orderId)) return new BaseDataResDto<>(Status.PARAMETERERROR);
        return shareOrderLogService.ifCanShareOrder(orderId, getUserId(maijiToken));
    }

    /**
     * 订单返现用户助力
     * @param baseDataReqDto
     * @param maijiToken
     * @return
     */
    @PostMapping("shareOrderHelp")
    public BaseDataResDto<Double> shareOrderHelp(@RequestBody BaseDataReqDto<String> baseDataReqDto, @RequestHeader("maijiToken") String maijiToken){
        String solId = baseDataReqDto.getData();
        if (StringUtil.isBlank(solId)) return new BaseDataResDto(Status.PARAMETERERROR);
        return shareOrderHelpLogService.shareOrderHelp(solId, getUserId(maijiToken));
    }

    /**
     * 查看订单返现分享助力详情（根据订单ID）
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findShareOrderHelpById")
    public BaseDataResDto<ShareOrderLogResData> findShareOrderHelpById(@RequestBody BaseDataReqDto<String> baseDataReqDto,
                                                                       @RequestHeader(name = "maijiToken", required = false) String token){
        String orderId = baseDataReqDto.getData();
        if (StringUtil.isBlank(orderId)) return new BaseDataResDto(Status.PARAMETERERROR);
        return shareOrderLogService.findShareOrderLogById(orderId, getUserId(token));
    }

    /**
     * 查看订单返现活动列表
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllShareOrderHelpLogs")
    public BaseMetaResDto<List<ShareOrderLogResData>> findAllShareOrderHelpLogs(@RequestBody BaseDataReqDto<ShareOrderLogFindAllData> baseDataReqDto,
                                                                      @RequestHeader(name = "maijiToken", required = false) String maijiToken){
        ShareOrderLogFindAllData data = baseDataReqDto.getData();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        return shareOrderHelpLogService.findAllShareOrderHelpLogs(data, metaData, getUserId(maijiToken));
    }

    /**
     * 用户提前结算订单返现分享助力
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("statisticShareOrderHelp")
    public BaseDataResDto<Double> statisticShareOrderHelp(@RequestBody BaseDataReqDto<String> baseDataReqDto){
        String helpId = baseDataReqDto.getData();
        if (StringUtil.isBlank(helpId)) return new BaseDataResDto<>(Status.PARAMETERERROR);
        return shareOrderLogService.statisticShareOrderHelp(helpId);
    }

    /**
     * 订单确认收货
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("orderConfirmReceived")
    public BaseResDto orderConfirmReceived(@RequestBody BaseDataReqDto<String> baseDataReqDto){
        String orderId = baseDataReqDto.getData();
        if (StringUtil.isBlank(orderId)) return new BaseDataResDto(Status.PARAMETERERROR);
        return shopingOrderService.orderConfirmReceived(orderId);
    }

    /**
     * 编辑订单
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("editOrder")
    public BaseResDto editOrder(@RequestBody BaseDataReqDto<ShopingOrderEditLogReqData> baseDataReqDto) {
        ShopingOrderEditLogReqData data = baseDataReqDto.getData();
        if (StringUtil.isNotBlank(data.getShopingAddressId()) || StringUtil.isNotBlank(data.getAreaInfoId()))
            return shopingAddressService.editOrder(data);
        else return shopingOrderService.editOrder(data);
    }

    /**
     *  获取订单修改记录列表
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllShopingOrderEditLogs")
    public BaseMetaResDto<List<ShopingOrderEditLog>> findAllShopingOrderEditLogs(@RequestBody BaseDataReqDto<ShopingOrderEditLogReqData> baseDataReqDto){
        ShopingOrderEditLogReqData data = baseDataReqDto.getData();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        return shopingOrderEditLogService.findAll(data, metaData);
    }

    /**
     * 上传运单号
     * @param param
     * @return
     */
    @PostMapping("uploudRefundNum")
    public BaseResDto uploudRefundNum(@RequestBody BaseDataReqDto<UploudRefundNumReqData> param){
		
    	if(StringUtils.isBlank(param.getData().getOrderId()) || StringUtils.isBlank(param.getData().getRefundNum())) return BaseResDto.baseResDto(Status.ERROR, "参数为空");
    	return shopingOrderService.uploudRefundNum(param);
    }

}